package com.css.dzj.dzjwgr.sys.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.aq.server.service.BaseService;
import com.css.dzj.dzjwgr.common.annotation.SysLog;
import com.css.dzj.dzjwgr.common.util.R;
import com.css.dzj.dzjwgr.common.validator.ValidatorUtils;
import com.css.dzj.dzjwgr.sys.user.entity.LoginUser;
import com.css.dzj.dzjwgr.sys.user.entity.User;
import com.css.dzj.dzjwgr.sys.user.form.LoginForm;
import com.css.dzj.dzjwgr.sys.user.service.impl.UserServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 登录逻辑
 * @author liangxg
 */
@RestController
@RequestMapping("/login")
@PropertySource(value = "classpath:base.properties")
public class LoginController {
    @Autowired
    UserServiceImpl userServiceImp;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;


    /*   @Value("${BASE_URL}")
       private String BASE_URL;
       @Value("${BASE_LOGIN_CONTROLLER}")
       private String BASE_LOGIN_CONTROLLER;*/
    @Autowired
    BaseService baseService;
    @SysLog("用户登录base")
    @PostMapping("/doLogin")
    public R loginAP(@RequestBody LoginForm loginForm, HttpSession session){
      /*  String url = BASE_URL + BASE_LOGIN_CONTROLLER;
        Map<String, String> param = new HashMap<>(2);
        param.put("loginName", loginForm.getLoginName());
        param.put("password", loginForm.getPassword());
        String resultMsg = HttpClientUtil.doPost(url, param);*/

        Map<String, Object> resultMap=baseService.doLogin(loginForm.getLoginName(),loginForm.getPassword());
        if(StringUtils.isEmpty(resultMap)){
            return R.error(500,"连接base服务器异常，请联系管理员解决");
        }else{
            JSONObject userInfo;
            /* Map<String, Object> resultMap = JSON.parseObject(resultMsg, Map.class);*/
            boolean success = (boolean)resultMap.get("success");
            if(success) {
                userInfo = (JSONObject) resultMap.get("result");
                LoginUser lu = JSON.parseObject(userInfo.toString(), LoginUser.class);
                session.setAttribute("_USER_LOGIN_INFO_",lu);
            }else{
                String message = resultMap.get("msg").toString();
                return R.error(500, message);
            }

            return R.ok().put("data", userInfo);
        }
    }
    /***
     * 登录验证
     * @param loginForm
     * @return
     */
    @SysLog("用户登录 withoutBase")
    @PostMapping("/checkUser")
    public R checkLogin(@RequestBody LoginForm loginForm,HttpServletResponse response) {
        try {
            //表单验证
            ValidatorUtils.validateEntity(loginForm);
            //获取登录用户名
            String userName = loginForm.getLoginName();
            //获取登录密码
            String password = DigestUtils.sha256Hex(loginForm.getPassword());
            User user = userServiceImp.findUserByNameAndPwd(userName, password);
            if (user == null || "".equals(user)) {
                return R.error(500,"用户不存在");
            }else {
                HttpSession session= request.getSession();
                session.setAttribute("userName",userName);
                Cookie cookie=new Cookie("userName",userName);
                cookie.setPath("/");
                response.addCookie(cookie);
                return R.ok("登录成功！");
            }

        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /***
     *退出逻辑
     * @return
     */
    @PostMapping("/logout")
    public R loginOut(HttpServletResponse response){
        try{
            HttpSession session= request.getSession();
            LoginUser userInfo=(LoginUser) session.getAttribute("_USER_LOGIN_INFO_");
            if(null==userInfo || StringUtils.isEmpty(userInfo)){
                return R.ok();
            }
            String userId=userInfo.getUserId().toString();
            session.removeAttribute("_USER_LOGIN_INFO_");
            Cookie cookie=new Cookie("userInfo","");
            cookie.setPath("/");
            response.addCookie(cookie);
            redisTemplate.delete("_USER_LOGIN_INFO_"+userId);
            //baseService.logSuccess(3, "退出登录", "2");
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage());
        }
    }

}
